﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using MotaWeb.Models.Interfaces;

namespace MotaWeb.Security
{
    /// <summary>
    /// Interface wrapper around provider to support unit testing
    /// </summary>
    public interface IMembershipService
    {
        int MinPasswordLength { get; }
        int MinUsernameLength { get; }

        bool ValidateUser(string userName, string password);
        MembershipCreateStatus CreateUser(string userName, string password, string email, out MembershipUser newUser);
        bool ChangePassword(string userName, string oldPassword, string newPassword);
        MembershipUserCollection GetAllUsers();
        MembershipUser GetUser(string userName);
        void UpdateUser(ISiteUser user);
    }

    public class AccountMembershipService : IMembershipService
    {
        private const int MIN_USERNAME_LENGTH = 4;
        private MembershipProvider _provider;

        public AccountMembershipService()
            : this(null)
        {
        }

        public AccountMembershipService(MembershipProvider provider)
        {
            _provider = provider ?? Membership.Provider;
        }

        public int MinPasswordLength
        {
            get
            {
                return _provider.MinRequiredPasswordLength;
            }
        }

        public int MinUsernameLength 
        {
            get
            {
                return MIN_USERNAME_LENGTH;
            }
        }

        public bool ValidateUser(string userName, string password)
        {
            return _provider.ValidateUser(userName, password);
        }

        public MembershipCreateStatus CreateUser(string userName, string password, string email, out MembershipUser newUser)
        {
            MembershipCreateStatus status;
            newUser = _provider.CreateUser(userName, password, email, null, null, true, null, out status);
            return status;
        }

        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */);
            return currentUser.ChangePassword(oldPassword, newPassword);
        }

        public MembershipUserCollection GetAllUsers()
        {
            int userCount = 0;
            return _provider.GetAllUsers(0, 100, out userCount);
        }

        public MembershipUser GetUser(string userName)
        {
            return _provider.GetUser(userName, false);
        }

        public void UpdateUser(ISiteUser user)
        {
            MembershipUser u = _provider.GetUser(user.ProviderUserKey, false);
            u.Email = user.Email;
            _provider.UpdateUser(u);
        }
    }
}
